package com.csh.auth.application.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.alibaba.fastjson.JSON;
import com.csh.auth.application.convert.AuthUserDtoConverter;
import com.csh.auth.application.dto.AuthUserDto;
import com.csh.auth.common.entity.Result;
import com.csh.auth.domain.entity.AuthUserBo;
import com.csh.auth.domain.service.AuthUserDomainService;
import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;

/**
 * 用户controller
 * @Author: Maverick_Csh
 * @Date: 2024/3/19
 */
@RestController
@RequestMapping("/user/")
@Slf4j
public class UserController {
    @Resource
    private AuthUserDomainService authUserDomainService;

    /**
     * 用户注册
     */
    @RequestMapping("register")
    public Result<Boolean> register(@RequestBody AuthUserDto authUserDto) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.register.dto:{}", JSON.toJSONString(authUserDto));
            }
            checkUserInfo(authUserDto);
            AuthUserBo authUserBo = AuthUserDtoConverter.INSTANCE.convertDtoToBo(authUserDto);
            return Result.ok(authUserDomainService.register(authUserBo));
        } catch (Exception e) {
            log.error("UserController.register.error:{}", e.getMessage(), e);
            return Result.fail("注册用户失败");
        }
    }

    /**
     * 修改用户信息
     */
    @RequestMapping("update")
    public Result<Boolean> update(@RequestBody AuthUserDto authUserDto) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.update.dto:{}", JSON.toJSONString(authUserDto));
            }
            checkUserInfo(authUserDto);
            AuthUserBo authUserBo = AuthUserDtoConverter.INSTANCE.convertDtoToBo(authUserDto);
            return Result.ok(authUserDomainService.update(authUserBo));
        } catch (Exception e) {
            log.error("UserController.update.error:{}", e.getMessage(), e);
            return Result.fail("修改用户信息失败");
        }
    }

    /**
     * 删除用户
     */
    @RequestMapping("delete")
    public Result<Boolean> delete(@RequestBody AuthUserDto authUserDto) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.delete.dto:{}", JSON.toJSONString(authUserDto));
            }
            AuthUserBo authUserBo = AuthUserDtoConverter.INSTANCE.convertDtoToBo(authUserDto);
            return Result.ok(authUserDomainService.delete(authUserBo));
        } catch (Exception e) {
            log.error("UserController.delete.error:{}", e.getMessage(), e);
            return Result.fail("修改用户信息失败");
        }
    }

    /**
     * 用户 启用/禁用
     */
    @RequestMapping("changeStatus")
    public Result<Boolean> changeStatus(@RequestBody AuthUserDto authUserDto) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.changeStatus.authUserDto:{}", JSON.toJSONString(authUserDto));
            }
            Preconditions.checkNotNull(authUserDto.getStatus(),"用户状态不能为空");
            AuthUserBo authUserBo = AuthUserDtoConverter.INSTANCE.convertDtoToBo(authUserDto);
            return Result.ok(authUserDomainService.changeStatus(authUserBo));
        } catch (Exception e) {
            log.error("UserController.changeStatus.error:{}", e.getMessage(), e);
            return Result.fail("用户 启用/禁用 失败");
        }
    }

    /**
     * 查询个人详情
     * @param authUserDto
     * @return
     */
    @RequestMapping("getUserInfo")
    public Result<AuthUserDto> getUserInfo(@RequestBody AuthUserDto authUserDto) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.getUserInfo.authUserDto:{}", JSON.toJSONString(authUserDto));
            }
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDto.getUserName()), "用户名不能为空");
            AuthUserBo authUserBo = AuthUserDtoConverter.INSTANCE.convertDtoToBo(authUserDto);
            AuthUserBo userInfo = authUserDomainService.getUserInfo(authUserBo);
            AuthUserDto userDto = AuthUserDtoConverter.INSTANCE.convertBoToDto(userInfo);
            return Result.ok(userDto);
        } catch (Exception e) {
            log.error("UserController.changeStatus.error:{}", e.getMessage(), e);
            return Result.fail("查询用户信息失败");
        }
    }

    /**
     * 用户退出
     * @param userName
     * @return
     */
    @RequestMapping("logOut")
    public Result logOut(@RequestParam String userName) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.logOut.userName:{}", userName);
            }
            Preconditions.checkArgument(!StringUtils.isBlank(userName), "用户名不能为空");
            StpUtil.logout(userName);
            return Result.ok();
        } catch (Exception e) {
            log.error("UserController.logOut.error:{}", e.getMessage(), e);
            return Result.fail("用户退出登录失败");
        }
    }

    // 用户输入验证码登陆时调用
    @RequestMapping("doLogin")
    public Result<SaTokenInfo> doLogin(@RequestParam("validCode") String validCode) {
        try {
            Preconditions.checkArgument(!StringUtils.isBlank(validCode),"验证码不能为空！");
            SaTokenInfo tokenInfo = authUserDomainService.doLogin(validCode);
            return Result.ok(tokenInfo);
        }catch (Exception e){
            log.error("UserController.doLogin.error:{}", e.getMessage(), e);
            return Result.fail("用户登陆失败");
        }
    }

    // 查询登录状态，浏览器访问： http://localhost:8081/user/isLogin
    @RequestMapping("isLogin")
    public String isLogin() {
        return "当前会话是否登录：" + StpUtil.isLogin();
    }

    private void checkUserInfo(@RequestBody AuthUserDto authUserDto) {
        Preconditions.checkArgument(!StringUtils.isBlank(authUserDto.getUserName()), "用户名不能为空");
        Preconditions.checkArgument(!StringUtils.isBlank(authUserDto.getEmail()), "用户邮箱不能为空");
//        Preconditions.checkArgument(!StringUtils.isBlank(authUserDto.getPassword()), "用户密码不能为空");
    }

    // 测试登录，浏览器访问http://localhost:3011/user/Login?name=zhang&pwd=123456
    @RequestMapping("/Login")
    public SaResult doLogin(String name, String pwd) {
        // 此处仅作模拟示例，真实项目需要从数据库中查询数据进行比对
        if("zhang".equals(name) && "123456".equals(pwd)) {
            StpUtil.login(10001);
            // 第2步，获取 Token 相关参数
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            // 第3步，返回给前端
            return SaResult.data(tokenInfo);
        }
        return SaResult.error("登录失败");
    }

}
